import React, { Component } from 'react'

export default class Chat extends Component {
  //声明状态 message 消息
  state = {
    msgs: [
      '你好么?',
      '我不好, 你咋样',
      '我还行, 吃多了就是'
    ],
    keyword: ''
  }

  //声明input元素的onchange事件回调
  save = (e) => {
    this.setState({
      keyword: e.target.value
    })
  }
  
  //声明按钮的单击事件回调
  send = () => {
    //获取表单元素的值
    let {keyword, msgs} = this.state;
    //更新msgs状态数据
    this.setState({
      msgs: [...msgs, keyword]
    })
  }

  render() {
    return (
      <div>
        <input type="text" value={this.state.keyword} onChange={this.save} /><button onClick={this.send}>发送</button>
        <hr />
        <div ref={el => this.div = el} style={{width: 400, height: 250, border: 'solid 1px #456', overflowY: 'scroll'}}>
          <ul>
            {
              this.state.msgs.map((item, index) => {
                return <li key={index}>{item}</li>
              })
            }
          </ul>
        </div>
      </div>
    )
  }

  //组件更新完成之后的回调
  componentDidUpdate(){
    //修改 div 垂直方向的滚动位置
    this.div.scrollTop = this.div.scrollHeight;
  }
}
